package com.mengzhilan.util;

import com.mengzhilan.constant.ApplicationConst;
import com.mengzhilan.constant.StartingParameterConst;
import com.mengzhilan.sql.MZLHomeSQLXmlFileHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xlp.db.xml.ClassPathSQLXmlFileHandler;
import org.xlp.db.xml.FilePathSQLXmlFileHandler;
import org.xlp.db.xml.SQLXmlContextApplicationUtils;
import org.xlp.stopwatch.StopWatch;
import org.xlp.utils.XLPStringUtil;

import java.io.File;

/**
 * 简化解析sql语句配置文件工具类
 */
public class SQLFileParseUtils {
    /**
     * 解析文件类型，文件或目录
     */
    private static final String TYPE_FILE = "file";
    //private static final String TYPE_DIRECTORY = "directory";

    private static final Logger LOGGER = LoggerFactory.getLogger(SQLFileParseUtils.class);

    /**
     * 解析sql语句配置文件
     */
    public static void parseSQLFile(){
        StopWatch stopWatch = new StopWatch();
        if (LOGGER.isDebugEnabled()){
            stopWatch.start();
            LOGGER.debug("正在开始解析sql语句配置文件。。。");
        }
        String type = System.getProperty(StartingParameterConst.SQL_CONFIG_FILE_TYPE);
        String fileName = System.getProperty(StartingParameterConst.SQL_CONFIG_FILE_PATH);
        boolean isFileType = TYPE_FILE.equals(type);
        if (isFileType){
            if (XLPStringUtil.isEmpty(fileName)){
                if (LOGGER.isWarnEnabled()){
                    LOGGER.warn("未配置生sql语句配置文件路径，跳过解析sql语句配置文件！");
                }
                return;
            }
        }
        if (XLPStringUtil.isEmpty(fileName)){
            fileName = ApplicationConst.DEFAULT_SQL_DIRECTORY;
        }
        File file = new File(ApplicationUtils.getConfigBaseDir(), fileName);
        if (file.exists()){
            SQLXmlContextApplicationUtils.addHandler(new MZLHomeSQLXmlFileHandler());
            SQLXmlContextApplicationUtils.addHandler(new ClassPathSQLXmlFileHandler());
            SQLXmlContextApplicationUtils.addHandler(new FilePathSQLXmlFileHandler());
            if (isFileType) {
                SQLXmlContextApplicationUtils.parseFile(file);
            } else {
                SQLXmlContextApplicationUtils.parseDirectory(file);
            }
            //把SQL上下文放入缓存中
            SQLXmlContextApplicationUtils.putToCache();
        } else {
            if (LOGGER.isErrorEnabled()){
                LOGGER.error("解析sql语句配置文件失败（文件不存在）！" + file.toString());
            }
        }
        if (LOGGER.isDebugEnabled()){
            LOGGER.debug("解析sql语句配置文件完成。。。所用时间为：" + stopWatch.stopAndFormatter());
        }
    }
}
